package cn.itsource.autoconfigure;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

public class RedisConfiguration {


    // Redis的连接工厂，通过次对象可以获取到Redis连接
    @Autowired
    private RedisConnectionFactory factory;

    /**
     * 使用JSON进行序列化
     * @return
     */
    @Bean
    public RedisTemplate<Object, Object> redisTemplate() {
        // 1.创建一个RedisTemplate对象
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        // 2.设置连接工厂
        redisTemplate.setConnectionFactory(factory);
        // 3.创建JSON格式序列化对象
        GenericFastJsonRedisSerializer serializer = new GenericFastJsonRedisSerializer();
        // 4.key的序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // 5.value的序列化
        redisTemplate.setValueSerializer(serializer);
        // 6.hash结构key的序列化
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        // 7.hash结构value的序列化
        redisTemplate.setHashValueSerializer(serializer);
        return redisTemplate;
    }
}
